<template>
  <div class="app-container-component">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="professions">
          <el-form-item label="文件类型" size="small">
            <el-select v-model="searchForm.type" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in global.creditworthinessListOther"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="文件名称" size="small">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" v-if="roleType === 0  || roleType === 1"
                 @click="addTeam()">添加
      </el-button>

      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      @openVisible="openVisible"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="80"
        v-if="roleType === 0  || roleType === 1"
      >
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.materialId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-publicitymaterials${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-publicitymaterials${scope.$index}`].doClose()">
                取消
              </el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-publicitymaterials${scope.$index}>
              删除
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="500px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="100px">
        <el-form-item label="文件类型" size="small">
          <el-select v-model="teamRow.type" placeholder="请选择">
            <el-option
              v-for="item in global.creditworthinessListOther"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" size="small" class="item-inline">
          <el-input type="text" v-model="teamRow.name"></el-input>
        </el-form-item>
        <el-form-item label="文件路径" size="small">
          <input type="file" ref='file' @change="fileUpload($event,'file')">
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small" v-if="isSubmit">文件上传中。。。{{precent}}%</el-button>
        <el-button type="warning" size="small" @click="submitForm('teamRow')" v-no-more-click v-if="!isSubmit">确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="文件查看" clas :visible.sync="imgVisible" width="800px">
      <img class="img-dialog" :src="`${global.exportUrl}${imgMsg.src}`" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    addPromotionalMaterials,
    selectPromotionalMaterials,
    deletePromotionalMaterials,
    updatePromotionalMaterials
  } from '@/api/publicitymaterials1'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'

  const type = function(row, column) {
    if (row.type) {
      let obj = {}
      obj = global.creditworthinessListOther.find((item) => {
        return item.value === row.type // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const filePath = {
    props: ['colConfig'],
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        <div>
<!--          <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看</a>-->
          <a v-if="scope.row[colConfig.prop]" target="_blank" :href="GLOBAL.filePathUrl1+encodeURI(scope.row[colConfig.prop])">下载</a>
        </div>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'name', label: '文件名称', minWidth: '30%' },
          { prop: 'type', label: '文件类型', minWidth: '30%', formatter: type },
          { prop: 'filePath', label: '文件', width: '150', component: filePath },
          { prop: 'remark', label: '备注说明', minWidth: '30%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增纳税社保审计',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {},
        visible: false,
        imgVisible: false,
        imgMsg: {},
        isSubmit: false, // 增加修改时判断文件是否上传完成
        precent: ''
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      }
    },
    methods: {
      upLoad(upLoad, params, callback1, callback2) {
        upLoad(params, function(progressEvent) { // 原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
            callback1(progressEvent)
          }
        }).then(res => {
          callback2(res.data)
        }).catch(() => {
          this.outerVisible = false
          this.isSubmit = false
          this.progress = ''
        })
      },
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.category = 3
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      fileClear() {
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增纳税社保审计'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        this.fileClear()
      },
      editTeam(materialId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改纳税社保审计'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.fileClear()
        const params = {
          materialId: materialId
        }
        selectPromotionalMaterials(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('category', 3)
        params.append('type', this.teamRow.type)
        params.append('name', this.teamRow.name || '')
        params.append('file', this.teamRow.file)
        params.append('remark', this.teamRow.remark || '')
        if (!this.dialogType) {
          params.append('materialId', this.teamRow.materialId)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              this.upLoad(addPromotionalMaterials, params, (res) => {
                const loaded = res.loaded
                const total = res.total
                this.$nextTick(() => {
                  this.isSubmit = true
                  this.precent = (loaded / total) * 100
                })
              }, (res) => {
                this.outerVisible = false
                this.isSubmit = false
                this.progress = ''
                this.fetchData()
              })
            } else {
              this.upLoad(updatePromotionalMaterials, params, (res) => {
                const loaded = res.loaded
                const total = res.total
                this.$nextTick(() => {
                  this.isSubmit = true
                  this.precent = (loaded / total) * 100
                })
              }, (res) => {
                this.outerVisible = false
                this.isSubmit = false
                this.progress = ''
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-publicitymaterials${scope.$index}`].doClose()
        const params = {
          materialId: scope.row.materialId,
          isDel: 1
        }
        deletePromotionalMaterials(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      fileUpload(event, teamRowName) {
        this.$set(this.teamRow, teamRowName, event.target.files[0])
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      }
    },
    mounted() {
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container-component {
    height: auto;

    .el-pagination {
      margin-top: 20px;
    }

    .table-btn {
      margin-bottom: 10px;

      & > button {
        margin: 0 20px;
      }

      .el-dialog {
        textarea {
          margin-top: 10px;
        }

        .el-checkbox {
          margin-right: 20px;
        }

        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }

    .item-inline {
      display: inline-block;
      width: 400px;
    }

    .img-dialog {
      max-width: 740px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
